/**
 * Created by 
 */
define(["avalon",
	"text!./breadcrumb_widget.html"], function(avalon, sourceHTML){

	var widget = avalon.ui.breadcrumbWidget = function(element, data, vmodels){

		var vmodel = avalon.define(data.breadcrumbWidgetId, function(vm){
			vm.breadCrumb = avalon.mix({}, data.breadcrumbWidgetOptions);
			vm.$currentState = {};
			vm.$Statechains = [];
			 // $breadcrumb: {
			 //        stateName:"albums.item",
			 //        guid: "",
			 //        title: ""
			 //      }

			



			vm.$init = function(){


				// root.$currentStateModel
				// avalon.each(avalon.router.routingTable.get,function(i,stateModel){
				// 	if(stateModel.stateName == vm.breadCrumb.stateName){
				// 		vm.$currentState = stateModel;

				// 		vm.$currentState.title = vm.breadCrumb.title || stateModel.title;


				// 	}
				// })
				vm.$currentState = avalon.vmodels.app.currentStateModel;

				vm.$currentState.title = vm.breadCrumb.title || vm.$currentState.title;


				
				var cs = vm.$currentState;

				_.each(vm.$currentState.chain, function(c){
					
					if(c != vm.$currentState){
						var r = {
							
							stateName: c.stateName
						}
						var nr = c.regexp.toString();
						
						r.regexp = new RegExp(nr.replace("$/i","").substr(1));
						
						r.path = (r.regexp.exec(vm.$currentState.path))[0];

						if(_.has(avalon.vmodels,c.vmName)){
							r.title = avalon.vmodels[c.vmName].$breadcrumb.title || c.title;
						}else{
							r.title = c.title;
						}
						

						vm.$Statechains.push(r);
						
					}else{
						vm.$Statechains.push({
							stateName: c.stateName,
							title:  cs.title,
							path:   cs.path,
							regexp: cs.regexp
						});
					}
					
					
				})

				element.innerHTML = sourceHTML;
              	avalon.scan(element, [vmodel].concat(vmodels));
			}

	  		vm.$remove = function(){

	  			element.innerHtml = element.textContent = "";
	  		}
		})
		return vmodel;
	}
	return avalon;
})
